package com.unisound.tracelog.server.ui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.unisound.tracelog.common.model.dto.ResultDTO;
import com.unisound.tracelog.server.model.entity.TraceLogTag;
import com.unisound.tracelog.server.service.TraceLogTagService;
import com.unisound.tracelog.server.ui.converter.TraceLogTagToResponseConverter;
import com.unisound.tracelog.server.ui.model.request.TraceLogTagSearchRequest;
import com.unisound.tracelog.server.ui.model.response.TraceLogTagResponse;
import com.unisound.tracelog.server.ui.service.UITraceLogTagService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UITraceLogTagServiceImpl implements UITraceLogTagService {

    @Autowired
    private TraceLogTagService traceLogTagService;

    @Autowired
    private TraceLogTagToResponseConverter traceLogTagToResponseConverter;

    @Override
    public ResultDTO<TraceLogTagResponse> search(TraceLogTagSearchRequest request) {
        if (!checkSearch(request)) return ResultDTO.success();

        LambdaQueryWrapper<TraceLogTag> wrapper = new LambdaQueryWrapper<>(TraceLogTag.builder()
                .tagKey(request.getTagKey())
                .tagValue(request.getTagValue())
                .build());
        wrapper.orderByDesc(TraceLogTag::getTraceId);
        List<TraceLogTag> traceLogTags = traceLogTagService.list(wrapper);

        List<TraceLogTagResponse> responses = traceLogTags.stream()
                .map(traceLogTag -> traceLogTagToResponseConverter.convert(traceLogTag))
                .collect(Collectors.toList());
        return ResultDTO.success(responses);
    }

    private boolean checkSearch(TraceLogTagSearchRequest request) {
        if (StringUtils.isEmpty(request.getTagKey())) return false;
        if (StringUtils.isEmpty(request.getTagValue())) return false;
        return true;
    }

}
